//后台管理系统长时间未操作退出登录
import {LOGIN_PATH} from "../assets/js/define";

export default {
    install(Vue, options = {}) {
        const timeout = options.timeout || 10 * 60 * 1000 // 默认10分钟
        let timer = null
        const resetIdleTimer = () => {
            clearIdleTimer()
            timer = setTimeout(() => {
                handleLogout()
            }, timeout)
        }

        const clearIdleTimer = () => {
            if (timer) {
                clearTimeout(timer)
                timer = null
            }
        }

        const handleLogout = () => {
            clearIdleTimer()
            // 清空 token
            this.$message.warning("您已长时间未操作，请重新登录")
            this.$api.userLogout().then(res => {
                this.$quinn.removeStorage("token");
                this.$quinn.removeStorage("userData");
                window.location.href = LOGIN_PATH;
            })
            if (Vue.prototype.$message) {
                Vue.prototype.$message.warning("您已长时间未操作，请重新登录")
            }
        }

        Vue.prototype.$idleLogout = {
            start() {
                resetIdleTimer()
                document.addEventListener("mousemove", resetIdleTimer)
                document.addEventListener("keydown", resetIdleTimer)
                document.addEventListener("click", resetIdleTimer)
            },
            stop() {
                clearIdleTimer()
                document.removeEventListener("mousemove", resetIdleTimer)
                document.removeEventListener("keydown", resetIdleTimer)
                document.removeEventListener("click", resetIdleTimer)
            }
        }
    }
}
